import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Upload, 
  Checkbox, 
  TimePicker, 
  Modal,
  message,
  Image
} from 'antd';
import { 
  PlusOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { shopInfo, editShopInfo } from '@/api/account';
import { serverUrl } from '@/utils/common';

const { TextArea } = Input;
const { RangePicker } = TimePicker;

const ShopManagement = () => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [loading, setLoading] = useState(false);

  // 获取店铺信息
  const getShopInfo = async () => {
    try {
      setLoading(true);
      const res = await shopInfo();
      form.setFieldsValue({
        ...res.data,
        date: res.data.date ? JSON.parse(res.data.date) : null,
        supports: res.data.supports ? JSON.parse(res.data.supports) : []
      });
      
      setFileList(res.data.pics.map(item => ({
        uid: item,
        name: item,
        status: 'done',
        url: serverUrl + item
      })));
    } catch (error) {
      message.error('获取店铺信息失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getShopInfo();
  }, []);

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      const formData = {
        ...values,
        date: JSON.stringify(values.date),
        supports: JSON.stringify(values.supports),
        pics: JSON.stringify(fileList.map(item => {
          if (item.response) {
            return item.response.imgUrl.split('/').pop();
          }
          return item.name;
        }))
      };

      const { code, msg } = await editShopInfo(formData);
      if (code === 0) {
        message.success(msg);
        getShopInfo();
      } else {
        message.error(msg);
      }
    } catch (error) {
      console.error('表单提交失败:', error);
    }
  };

  // 图片上传前的校验
  const beforeUpload = (file) => {
    const isImage = file.type.includes('image');
    if (!isImage) {
      message.error('只能上传图片文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
    }
    return isImage && isLt2M;
  };

  // 处理图片预览
  const handlePreview = async (file) => {
    setPreviewImage(file.url || file.thumbUrl);
    setPreviewVisible(true);
  };

  // 处理图片变化
  const handleChange = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  // 处理头像上传成功
  const handleAvatarSuccess = (res) => {
    form.setFieldsValue({ avatar: res.imgUrl });
  };

  // 店铺活动选项
  const supportOptions = [
    '单人精彩套餐',
    'VC无限橙果汁全场8折',
    '在线支付满28减5',
    '特价饮品八折抢购',
    '中秋特惠',
    '国庆特价',
    '春节1折折扣'
  ];

  return (
    <div style={{ padding: 20 }}>
      <Card 
        title="店铺信息管理" 
        style={{ maxWidth: 900, margin: '0 auto' }}
        loading={loading}
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
        >
          <Form.Item
            label="店铺名称"
            name="name"
            rules={[{ required: true, message: '请输入店铺名称' }]}
          >
            <Input placeholder="请输入店铺名称" />
          </Form.Item>

          <Form.Item
            label="店铺公告"
            name="bulletin"
          >
            <TextArea rows={3} placeholder="请输入店铺公告" />
          </Form.Item>

          <Form.Item
            label="店铺头像"
            name="avatar"
          >
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/api/shop/upload"
              beforeUpload={beforeUpload}
              onChange={({ file }) => {
                if (file.status === 'done') {
                  handleAvatarSuccess(file.response);
                }
              }}
            >
              {form.getFieldValue('avatar') ? (
                <img
                  src={serverUrl + form.getFieldValue('avatar')}
                  alt="avatar"
                  style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                />
              ) : (
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传头像</div>
                </div>
              )}
            </Upload>
          </Form.Item>

          <Form.Item
            label="商品图片"
          >
            <Upload
              action="/api/shop/upload"
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
              beforeUpload={beforeUpload}
            >
              {fileList.length >= 8 ? null : (
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              )}
            </Upload>
          </Form.Item>

          <Form.Item
            label="起送价格"
            name="minPrice"
            rules={[{ required: true, message: '请输入起送价格' }]}
          >
            <Input type="number" />
          </Form.Item>

          <Form.Item
            label="送达时间"
            name="deliveryTime"
          >
            <Input placeholder="例如：30分钟" />
          </Form.Item>

          <Form.Item
            label="配送备注"
            name="description"
          >
            <TextArea rows={4} placeholder="请输入配送备注" />
          </Form.Item>

          <Form.Item
            label="店铺好评率"
            name="score"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="店铺销量"
            name="sellCount"
          >
            <Input type="number" />
          </Form.Item>

          <Form.Item
            label="店铺活动"
            name="supports"
          >
            <Checkbox.Group options={supportOptions} />
          </Form.Item>

          <Form.Item
            label="营业时间"
            name="date"
            style={{ width: '100%' }}
          >
            <RangePicker 
              format="HH:mm"
              placeholder={['开始时间', '结束时间']}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 18 }}>
            <Button type="primary" onClick={submitForm}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Modal
        visible={previewVisible}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <Image
          src={previewImage}
          style={{ width: '100%' }}
        />
      </Modal>
    </div>
  );
};

export default ShopManagement;